﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text.pdf;
using iTextSharp.text;
using Rectangle = iTextSharp.text.Rectangle;

namespace PdfMerger
{
    public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string pad1path = this.textBox1.Text;
            string pad2path = this.textBox2.Text;
            string[] files = { pad1path, pad2path };
            string outputFile = @"C:\Users\Huang\Desktop\新建文件夹\merged_output.pdf";
            MergePdfFiles(files, outputFile);
        }





        public static void MergePdfFiles(string[] files, string outputFile)
        {
            using (FileStream fs = new FileStream(outputFile, FileMode.Create))
            {
                Document document = null;

                PdfCopy copy = null;
                PdfReader reader = null;

                try
                {
                    document = new Document();
                    copy = new PdfCopy(document, fs);
                    document.Open();

                    foreach (string file in files)
                    {
                        reader = new PdfReader(file);
                        int numberOfPages = reader.NumberOfPages;

                        for (int i = 1; i <= numberOfPages;)
                        {
                            Rectangle pageSize = reader.GetPageSizeWithRotation(i);
                            float width = pageSize.Width;
                            float height = pageSize.Height;

                            // 这里可以调整页面尺寸和方向  
                            // 如果需要保持原样，则不需要修改  

                            PdfImportedPage page = copy.GetImportedPage(reader, i);
                            copy.AddPage(page);
                            i++;
                        }

                        reader.Close();
                    }
                }
                finally
                {
                    if (document != null)
                    {
                        document.Close();
                    }

                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
            }
        }







    }
}
